<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="700px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <!-- <template #selectA="{ model, field }">
        
      </template> -->
    </BasicForm>
    <Divider type="vertical" ></Divider>
    <div ref="tableRef">
      <BasicTable @register="registerTable">
        <template #checked="{ record }">
          <Switch  
            v-model:checked="record.checked" 
            checked-children="启用" size="default"
            un-checked-children="禁用" 
          />
        </template>
      </BasicTable>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { Divider, Switch } from 'ant-design-vue';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema, extLdpColumns  } from './data';
import { saveOrUpdate, getClient, listExtLdpConn } from './api';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import { useMessage } from '/@/hooks/web/useMessage';
import { PageEnum } from '/@/enums/pageEnum';
const { createMessage } = useMessage();
const tableRef = ref<HTMLElement>()
// 声明Emits
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref('1');
const authorizedGrantTypes = ref([])
const record = ref<any>()

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  schemas: formSchema,
  showActionButtonGroup: false,
  wrapperCol: { lg: 24, md: 24 }
});

const actionColumn: BasicColumn = {
  width: 60,
  title: '操作',
  dataIndex: 'action',
  helpMessage: '由处理业务的主租户管理, 管理场景租户一般不做配置',
  fixed: 'right',
  slot: 'tableActions',
  actions:  (record: Recordable) => [
    {
      label: '去配置',
      onClick: handleGoConfig.bind(null, record),
    },
  ],

}

const [registerTable, { reload, setProps, getDataSource }] = useTable({
  title: '外部身份源',
  columns: extLdpColumns,
  api: listExtLdpConn,
  rowKey: 'grantType',
  immediate: false,
  showIndexColumn: false,
  striped: true,
  useSearchForm: false,
  showTableSetting: false,
  clickToRowSelect: false,
  pagination: false,
  bordered: false,
  // 是否可以自适应高度
  // canResize: false,
  actionColumn,
  scroll: {
    y: 10000
  }
});

const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
  await resetFields();
  record.value = data.record
  console.log('record: ', data.record);

  setDrawerProps({ confirmLoading: false, showFooter: true, loading: true })
  try {
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.isDetail ? '1' : '0'
    if (unref(isUpdate)) {
      if (record.value.authorizedGrantTypes) {
        authorizedGrantTypes.value = record.value.authorizedGrantTypes.split(',')
      }
      setProps({ searchInfo: { id: unref(record.value.id) } });

      await setFieldsValue({
        ...record.value, 
        isDetail: isDetail.value, 
        authorizedGrantTypes: unref(authorizedGrantTypes)
      });
    }
    reload()
  } finally {
    setDrawerProps({ loading: false })
  }
});

const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));


const handleGoConfig = (record) => {
  window.open(`${PageEnum.CONFIG_CENTER}?configKey=${record.configKey}`)
}
async function handleSubmit(v) {
  try {
    const extGrantTypes = await getDataSource().filter(e => e.checked).map(e => e.grantType).join(',')
    if (isDetail.value === '1') {
      closeDrawer();
      return
    }
    let values = await validate();
    values.roleIds = values.roleIds ? values.roleIds.split(',') : undefined
    setDrawerProps({ confirmLoading: true });

    const form = { ...values, extGrantTypes }
    console.log('form', form);
    
    await saveOrUpdate(form, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`${unref(title)}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

<style lang="less">
// .ant-table td { white-space: nowrap; }
</style>
